package com.itcoon.cloud.framework.webmvc.exception.handler;

import com.itcoon.cloud.framework.ex.errorcode.CommonServiceErrorCode;
import com.itcoon.cloud.framework.webmvc.response.ApiResponse;
import com.itcoon.cloud.framework.webmvc.utils.ApiResponseUtils;
import com.itcoon.cloud.framework.webmvc.config.properties.GlobalWebConfigProperties;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

public class MethodArgumentNotValidExceptionHandler extends ParamsExceptionHandler<MethodArgumentNotValidException>{

    private final GlobalWebConfigProperties properties;

    public MethodArgumentNotValidExceptionHandler(GlobalWebConfigProperties properties) {
        this.properties = properties;
    }

    @Override
    public boolean support(Exception e) {
        return e instanceof MethodArgumentNotValidException;
    }

    @Override
    public void handle(HttpServletResponse response, MethodArgumentNotValidException e) {
        loopLog(e);
        BindingResult bindingResult = e.getBindingResult();
        List<String> parameterExceptionMessages = doParamsEx(bindingResult.getFieldErrors(), bindingResult.getTarget());
        ApiResponseUtils.writeJsonResponse(response, ApiResponse.error(CommonServiceErrorCode.BAD_PARAMETER.getCode(), CommonServiceErrorCode.BAD_PARAMETER.getMessage(), parameterExceptionMessages), properties.getResponse().getBizExceptionHttpStatus().value());
    }


}
